<?php

namespace App\Repository;

use App\Common\Libs\ArrayHelper;
use App\Models\LogCount;
use Illuminate\Support\Facades\DB;

/**
 * @package App\Repository
 * @see LogCountRepository
 */
class LogCountRepository extends BaseRepository
{
    public function createLogCount($loadData)
    {
        $model = $this->getLogCount($loadData);
        if ($model) {
            return true;
        }

        $currentTime = time();
        $tableName = $this->getTableName($currentTime);
        $this->createTable($tableName);

        return LogCount::setTableName($tableName)->create($loadData);
    }

    public function getLogCount($condition)
    {
        $currentTime = time();
        $tableName = $this->getTableName($currentTime);
        $this->createTable($tableName);

        $logCount = LogCount::setTableName($tableName)
            ->where('send_user_id', $condition['send_user_id'])
            ->where('receive_user_id', $condition['receive_user_id'])
            ->where('target_id', $condition['target_id'])
            ->where('target_type', $condition['target_type'])
            ->where('action_id', $condition['action_id'])
            ->where('action_type', $condition['action_type'])
            ->first();
        return $logCount ? true : false;
    }

    private function createTable($tableName)
    {
        $tables = DB::select('SHOW TABLES');
        $tables = ArrayHelper::getColumn($tables, 'Tables_in_' . env('DB_DATABASE'));

        if (!in_array($tableName, $tables)) {
            DB::select('CREATE TABLE IF NOT EXISTS `' . $tableName . '` (LIKE `log_count_202001`);');
        }

        return true;
    }

    private function getTableName($time)
    {
        $tableName = 'log_count_';
        $year = date('Y', $time);
        $season = ceil((date('n', $time)) / 3);
        $season = str_pad($season, 2, '0', STR_PAD_LEFT);
        $tableName .= $year . $season;
        return $tableName;
    }
}
